package com.tsfyun.scm.gateway.support.dd;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class ExceptionDingTalkMessage {

    private DingTalkMessageBuilder builder;

    private List<String> urls;

    public ExceptionDingTalkMessage(DingTalkMessageBuilder builder, List<String> urls) {
        this.builder = builder;
        this.urls = urls;
    }

    public void send() {
        Map<Integer,String> urlMap = Maps.newHashMap();
        int currentNum = ThreadLocalRandom.current().nextInt(urls.size());
        String json = "";
        try {
            json = builder.build();
            if(CollUtil.isNotEmpty(urls)) {
                for(int i=0;i < urls.size();i++) {
                    urlMap.put(i,urls.get(i));
                }
            }
            String responseJson = HttpUtil.post(urlMap.get(currentNum), json);
            //此处需判断错误码等等
            JSONObject jsonObject = JSONObject.parseObject(responseJson);
            int errcode = jsonObject.getInteger("errcode");
            if(0 != errcode) {
                throw new RuntimeException("发送失败，重试");
            }
        } catch (Exception e) {
            log.error("请求异常",e);
            //请求异常，尝试另外一个发送，跟首次发送的不一样
            Set<Integer> urlNumSet = urlMap.keySet();
            for(Integer number : urlNumSet) {
                if(number != currentNum) {
                    HttpUtil.post(urlMap.get(number), json);
                    break;
                }
            }
        }
    }
}